/*
Copyright The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package roletracker

import (
	"testing"

	"github.com/go-logr/logr"
	"github.com/go-logr/logr/funcr"
)

func TestWithReplicaRole(t *testing.T) {
	tests := []struct {
		name     string
		tracker  *RoleTracker
		expected string
	}{
		{
			name:     "nil tracker returns standalone",
			tracker:  nil,
			expected: RoleStandalone,
		},
		{
			name:     "leader tracker returns leader",
			tracker:  NewFakeRoleTracker(RoleLeader),
			expected: RoleLeader,
		},
		{
			name:     "follower tracker returns follower",
			tracker:  NewFakeRoleTracker(RoleFollower),
			expected: RoleFollower,
		},
		{
			name:     "standalone tracker returns standalone",
			tracker:  NewFakeRoleTracker(RoleStandalone),
			expected: RoleStandalone,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			baseLogger := funcr.New(func(prefix, args string) {
			}, funcr.Options{})

			logger := WithReplicaRole(baseLogger, tc.tracker)

			if logger == (logr.Logger{}) {
				t.Error("WithReplicaRole returned zero-value logger")
			}

			role := GetRole(tc.tracker)
			if role != tc.expected {
				t.Errorf("Expected role %q, got %q", tc.expected, role)
			}
		})
	}
}

func TestNewLogConstructor(t *testing.T) {
	tests := []struct {
		name     string
		tracker  *RoleTracker
		expected string
	}{
		{
			name:     "nil tracker",
			tracker:  nil,
			expected: RoleStandalone,
		},
		{
			name:     "leader tracker",
			tracker:  NewFakeRoleTracker(RoleLeader),
			expected: RoleLeader,
		},
		{
			name:     "follower tracker",
			tracker:  NewFakeRoleTracker(RoleFollower),
			expected: RoleFollower,
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			constructor := NewLogConstructor(tc.tracker, "test-controller")

			if constructor == nil {
				t.Fatal("NewLogConstructor returned nil")
			}

			logger := constructor(nil)
			if logger == (logr.Logger{}) {
				t.Error("LogConstructor returned zero-value logger")
			}
		})
	}
}
